//index.js
//获取应用实例
var timer = '';
const app = getApp()
Page({

  data: {
    scrollTop: 0,
    //banner轮播图
    list_banner: '',
    banner_heddin: false,
    imgurl: app.urlimg,
    //获取页面的宽度
    windowWidth: '',
    day_num: [
      { date_nj: '', text: '已开抢' },
    ],
    select_index: '',
    //产品列表
    product_box: [

    ],
    //时间戳存储
    time_all: [],
    // 页数
    page: '1',
    pagesize: 10,
    drop_load: true,
  },
  // banner点击
  photolink: function (e) {
    var that = this
    var url = e.currentTarget.dataset.url
    if (url !== '') {
      wx.redirectTo({ url: url })
    }
  },
  // 监听滚动事件
  scrollTop: function (e) {
    var that = this;
    var banner_heddin = false;
    if (e.detail.scrollTop > 140) {
      banner_heddin = true;
    }
    that.setData({
      banner_heddin: banner_heddin,
    })
  },
  /*点击进入详情页 */

  coomodityTAP: function (e) {
    var that = this;
    var fid = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../index/detail/index?id=' + fid
    })
  },



  //事件处理函数
  // 页头的切换
  click: function (e) {
    console.log(wx.getStorageSync('token_key'))
    var that = this;
    //加载参数
    var ids = e.currentTarget.dataset.ids;
    console.log(e);
    var page = 1;
    var pagesize = that.data.pagesize;

    //点击根据时间查询
    wx.request({
      url: app.url + '?controller=api_goods&action=get_promotion_list&promotion_id=' + ids,
      method: 'GET',
      data: {
        "page": page,
        "pagesize": pagesize,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      success: function (res) {
        console.log(res.data.result);
        // if (res.data.result == '') {
        // 	res.data.result = that.data.product_box;
        // }
        that.setData({
          // product: res.data.result,
          select_index: e.currentTarget.dataset.num,
          product_box: res.data.result,
          page: page,
          pagesize: pagesize,
          ids: ids,
          scrollTop: 0,
        })
        var product = res.data.result;
        for (var i = 0; i < product.length; i++) {
          if (product[i].s_time > 0) {

            //获得后台转过来的毫秒数 储存在time_box中
            that.data.time_all.push(product[i].s_time)
            // that.data.product_box.push(product[i])
            // 获得毫秒数  转化  成小时、分钟、秒
            that.time_cipher(product[i].s_time, i);
          } else {

            //获得后台转过来的毫秒数 储存在time_box中
            that.data.time_all.push(product[i].t_time)
            // that.data.product_box.push(product[i])
            // 获得毫秒数  转化  成小时、分钟、秒
            that.time_cipher(product[i].t_time, i);
          }
        }

      },
      //接口调用失败返回的函数
      fail: function (err) {
        console.log(err)
      }
    })

  },

  onLoad: function () {
    var that = this;
    var token_key = wx.getStorageSync('token_key');
    console.log(token_key);

    app.app_load(load_fn);

    function load_fn() {
      var windowWidth = '';
      //获取页面的宽度（用于页头的滚动）
      wx.getSystemInfo({
        success: function (res) {
          windowWidth = res.windowWidth / 5;
        }
      })

      //获取当前时间（用于页头的日期）
      var time_all = new Date();
      console.log(time_all);
      //获取三天前的时间
      time_all.setTime(time_all.getTime() - (24 * 60 * 60 * 1000) * 4);
      //计算天数函数
      function time_method() {
        time_all.setTime(time_all.getTime() + (24 * 60 * 60 * 1000) * 1);
        return (time_all.getMonth() + 1) + "/" + time_all.getDate();
      }
      var day_num_all = [];
      for (var i = 0; i < 7; i++) {
        // day_num_all.push(time_method())
        day_num_all[i] = {};
        var time_method_time = time_method();
        day_num_all[i].date_nj = time_method_time;
        console.log(day_num_all[i]);
        var timestamp1 = Date.parse(new Date(time_method_time));
        timestamp1 = timestamp1 / 1000;
        var timestamp2 = (new Date().getMonth() + 1) + '/' + new Date().getDate();
        timestamp2 = Date.parse(new Date(timestamp2)) / 1000;
        if (timestamp1 <= timestamp2) {
          day_num_all[i].state = '已开始';
        } else if (timestamp1 > timestamp2) {
          day_num_all[i].state = '即将开团';
        } else {
          day_num_all[i].state = '开团中';
        }
      }

      wx.request({
        url: app.url + 'api_banner/get_banner',
        data: {
          type: 1, // 1 限时抢购 2 拼团 3 抽奖团
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        }, success: function (res) {
          that.setData({
            list_banner: res.data.result,
          })
        }
      })

      //顶部导航数据请求
      wx.request({
        url: app.url + '?controller=api_goods&action=getPromotionLimitTime',
        method: 'GET',
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        },

        success: function (res) {
          console.log(res.data.result);
          // var selet_num = 3;//获取当前的日期
          // console.log(day_num_all[selet_num]);//获取当前的日期
          var all = [];
          for (var i = 0; i < day_num_all.length; i++) {
            if (res.data.result[i] != undefined) {
              all.push(res.data.result[i]);
            }
          }
          // var select_index = '';
          // var num = 1;
          // console.log(new Date(all[0].date).getTime() > new Date().getTime());
          // if (new Date(all[0].date).getTime() > new Date().getTime()) {
          //   select_index = 0;
          // } else {
          //   list();
          //   function list() {
          //     for (var i = 0; i <= all.length - num; i++) {
          //       // if (all[i].date_nj == day_num_all[selet_num]) {
          //       if (all[i].state == "开抢中") {
          //         return select_index = i;
          //       } else {
          //         if (i == selet_num) {
          //           selet_num--;
          //           list();
          //         }
          //       }
          //     }
          //   }
          // }
          // if (select_index != '') {
          //   var ids = all[select_index].ids;
          // } else {
          //   var ids = all[0].ids;
          // }
          var ids, select_index;
          for (var i in all){
            if (all[i].index){
              ids = all[i].ids;
              select_index= i;
            }
          }
          that.setData({
            day_num: all,
            select_index: select_index,
            ids: ids,
          })
          console.log(that.data.ids);


          //列表数据请求
          wx.request({
            //  url: app.url + "?controller=api_goods&action=get_promotion_list&promotion_id",
            url: app.url + '?controller=api_goods&action=get_promotion_list&promotion_id=' + that.data.ids,
            method: 'GET',
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token_key')
            },
            success: function (res) {
              console.log(res);
              var product = '';

              if (res.data.result instanceof Array) {
                product = res.data.result;
                that.setData({
                  product_box: product,
                });
                console.log(product);
                for (var i = 0; i < product.length; i++) {
                  if (product[i].s_time > 0) {

                    //获得后台转过来的毫秒数 储存在time_box中
                    that.data.time_all.push(product[i].s_time)
                    // that.data.product_box.push(product[i])
                    // 获得毫秒数  转化  成小时、分钟、秒
                    that.time_cipher(product[i].s_time, i);
                  } else {

                    //获得后台转过来的毫秒数 储存在time_box中
                    that.data.time_all.push(product[i].t_time)
                    // that.data.product_box.push(product[i])
                    // 获得毫秒数  转化  成小时、分钟、秒
                    that.time_cipher(product[i].t_time, i);
                  }
                }
              } else {
                clearTimeout(timer);
                that.setData({
                  product_box: product,
                });
              }

            },
            //接口调用失败返回的函数
            fail: function (err) {
              console.log(err)
            }
          })

        },
        //接口调用失败返回的函数
        fail: function (err) {
          console.log(err)
        }
      });
    }

  },
  // 获得毫秒数  转化  成小时、分钟、秒
  time_cipher: function (Times, index) {
    var that = this;

    Times -= 1;//减去一秒

    var day = Math.floor(Times / (60 * 60 * 24));//计算剩余的天数
    if (('' + day).length == 1) {
      day = '0' + day;
    }
    var hours = parseInt(Times / 60 / 60 % 24, 10); //计算剩余的小时
    if (('' + hours).length == 1) {
      hours = '0' + hours;
    }
    var minutes = parseInt(Times / 60 % 60, 10);//计算剩余的分钟
    if (('' + minutes).length == 1) {
      minutes = '0' + minutes;
    }
    var seconds = parseInt(Times % 60, 10);//计算剩余的秒数
    if (('' + seconds).length == 1) {
      seconds = '0' + seconds;
    }
    //倒计时判断
    var new_time = '';
    if (day <= '00' && hours <= '00' && minutes <= '00' && seconds <= '00') {
      new_time = 0;
    } else {
      new_time = day + "天" + hours + "时" + minutes + "分" + seconds + "秒";//排列时间
    }

    var product_box = that.data.product_box;//获取产品
    product_box[index].end_time = new_time;
    var time_all = that.data.time_all;//获取时间戳
    time_all[index] = Times;

    that.setData({
      product_box: product_box,
      time_all: time_all,
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  // onReachBottom:
  Reach_Bottom: function () {
    // clearTimeout(timer);
    var that = this;
    if (that.data.drop_load) {
      that.setData({
        drop_load: false,
      })
      console.log("上拉加载更多....")
      var page = that.data.page;
      ++page;
      var pagesize = that.data.pagesize;
      //数据加载
      wx.request({
        url: app.url + '?controller=api_goods&action=get_promotion_list&promotion_id=' + that.data.ids,
        method: 'GET',
        data: {
          "page": page,
          "pagesize": pagesize,
        },
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token_key')
        },
        success: function (res) {
          console.log(res.data.result);
          if (res.data.result.length) {
            wx.showToast({
              title: '加载中...',
              icon: 'loading',
              duration: 1200,
              mask: false,
            })
            var result = res.data.result;
            var product_box = that.data.product_box;
            for (var i = 0; i < result.length; i++) {
              product_box.push(result[i]);
            }
            that.setData({
              page: page,
              pagesize: pagesize,
              product_box: product_box,
            })
            //倒计时
            var product = res.data.result;
            for (var i = 0; i < product.length; i++) {
              //获得后台转过来的毫秒数 储存在time_box中
              that.data.time_all.push(product[i].t_time)
              // 获得毫秒数  转化  成小时、分钟、秒
              that.time_cipher(product[i].t_time, i);
            }
          } else {
            console.log(8555);
            //提示信息
            wx.showToast({
              title: '已经到底部咯~',
              icon: 'loading',
              duration: 1000,
            });
          }
        },
        //接口调用失败返回的函数
        fail: function (err) {
          console.log(err)
        },
        complete: function () {//接口调用结束的回调函数
          that.setData({
            drop_load: true,
          })
        }
      })
    }
  },
  onHide: function () {
    clearTimeout(timer);
  },
  onUnload: function () {
    clearTimeout(timer);
  },
  onShow: function () {
    var that = this;
    timer = setInterval(function () {
      var product = that.data.product_box;
      var time_all = that.data.time_all;
      for (var i = 0; i < product.length; i++) {
        that.time_cipher(time_all[i], i)
      }
    }, 1000)
  },
  //分享
  onShareAppMessage: function () {

  },
})
